#!/usr/bin/python
# Copyright 2004 -solar
# Distributed under the terms of the GNU General Public License v2
# $Header: $

import sys

if len(sys.argv) < 2:
	print "Usage: tbz2ipkg </path/package.tbz2> ..."
	sys.exit(1)

import os, xpak, string, socket

os.umask(0022)

# If we are not using this tool from a gentoo system it should still
# function so we only want to import portage system unless we are only a
# gentoo system.

if os.path.exists("/etc/gentoo-release"):
	vendor = "Gentoo"
	import portage
else:
	vendor = "Generic"

def tbz2ipk(tbz2ball):
	use=[]; iuse=[];
	priority = "optional";
	licence="";
	depend="";
	desc=os.path.basename(tbz2ball)+"\n";
	arch="Unknown\n";

	if not os.path.exists(tbz2ball):
		print "File: "+tbz2ball+" does not appear to exist."
		sys.exit(1)

	tmpdir = "/var/tmp/portage/ipkg/"
	if not os.path.exists(tmpdir):
		os.mkdir(tmpdir)
	tmpdir = tmpdir + os.path.basename(tbz2ball)+"/"

	tbz2file = xpak.tbz2(tbz2ball)

	ipkg = tmpdir+"/package.ipk"

	keys = tbz2file.filelist()

	if not os.path.exists(tmpdir):
		os.mkdir(tmpdir)

	if not os.path.exists(tmpdir+"/data/"):
		os.mkdir(tmpdir+"/data/")

	# open the cntrol file and print mapping values.
	control_file = tmpdir+"control"

	if os.path.exists(control_file):
		os.unlink(control_file)

	for key in keys:
		val = " ".join(tbz2file.getfile(key).split())

		if val != "":
			if key == "CHOST":
				chost = val
			if key == "CFLAGS":
				cflags = val
			if key == "PF":
				package = val
				key = "Package"
			if key == "PV":
				version = val
				key = "Version"
			if key == "RDEPEND":
				depend = val;
				key = "Depends"
			if key == "ARCH":
				arch = val
			key = "Architecture"
			if key == "CATEGORY":
				section = val
				key = "Section"
			if key == "LICENSE":
				licence = val
				key = "License"

			if key == "environment.bz2":
				val = tbz2file.getfile(key)
				fp=open(tmpdir+key, "wb")
				fp.write(tbz2file.getfile(key))
				fp.flush()
				fp.close()

				os.system("bzcat "+ tmpdir + key +" > "+tmpdir+"/env")

				# FIXME: use native API and get this in a buffer.
				os.system("grep ^ARCH= "+tmpdir+"/env | cut -d = -f 2 > "+tmpdir+"/arch")
				os.system("grep ^DESCRIPTION= "+tmpdir+"/env | awk -F = '{print $2}' >"+tmpdir+"/desc")

				fp = open(tmpdir+"/arch", "rb")
				arch = fp.read()
				fp.close()

				fp = open(tmpdir+"/desc", "rb")
				desc = fp.read()
				fp.close()

				os.unlink(tmpdir+"/desc")
				os.unlink(tmpdir+"/arch")
				os.unlink(tmpdir+key)
				val = ""

			if key == "USE":
				use = string.split(val, " ")
			if key == "IUSE":
				iuse = string.split(val, " ")
			# actually we might not want to map unknowns.
			if val != "":
				sys.stdout.write(key+": "+val + "\n")

	# Open the control file and write to it.
	fp = open(control_file, "w")
	fp.write("Package: " + package + "\n")
	fp.write("Architecture: " + arch )
	fp.write("Description: " + desc )
	fp.write("Licence: " + licence + "\n")
	fp.write("Vendor: " + vendor + "\n")
	fp.write("Depend: " + depend + "\n")
	fp.write("Iuse: " +string.join(iuse) +"\n")
	fp.write("Use: " + string.join(use) + "\n")

	if os.environ['USER']:
		fp.write("Maintainer: " +os.environ['USER'] + "@"+socket.gethostname()+"\n")

	# map IUSE->USE and look for build flag set in both. 
	# if set then we change the package priority from optional to required.
	for x in iuse:
		for y in use:
			if x == y:
				if x == "build":
					priority = "required"
					# break

	fp.write("Priority: " + priority + "\n")
	fp.write("#CHOST: " + chost + "\n")
	fp.write("#CFLAGS: " + cflags + "\n")
	fp.flush()
	fp.close()

	ret = os.system("/bin/tar -jxpf "+ tbz2ball + " -C" + tmpdir+"/data/ 2>/dev/null || :")

	if vendor == "Gentoo":
		for x in ['doc', 'info', 'man', 'html', 'sgml']:
			if "no"+x in portage.features:
				ret = os.system("/bin/rm -rf "+tmpdir+"/data/usr/share/"+x)
				ret = os.system("/bin/rm -rf "+tmpdir+"/data/usr/X11R6/share/"+x)

	# really need to find . -name '*.a' | xargs rm -rf
	for x in ['/usr/include', '/usr/lib/*.a', '/usr/lib/*.la']:
		#print "/bin/rm -rf "+tmpdir+"/data/"+x
		ret = os.system("/bin/rm -rf "+tmpdir+"/data/"+x)

	os.chdir(tmpdir)
	ret = os.system("cat control")
	if os.path.exists("./control.gz"):
		os.unlink("./control.gz")
	ret = os.system("/bin/gzip ./control")

	os.chdir(tmpdir+"/data/")
	ret = os.system("/bin/tar -zcpf ../data.tar.gz ./")
	ret = os.system("/bin/rm -rf "+tmpdir+"/data/")

	os.chdir(tmpdir)
	os.system("tar -zcf "+ipkg+" ./control.gz ./data.tar.gz ./env")
	os.system("mv "+ipkg+" `dirname "+tbz2ball+"``basename $PWD .tbz2`.ipk")

	os.unlink("./control.gz")
	os.unlink("./env")
	os.unlink("./data.tar.gz")
	# just for kix..
	os.system("find . -ls")




for x in sys.argv[1:]:
	tbz2ipk(x)
sys.exit(0)
